package com.example.dmgame.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.dmgame.bean.ChapterCommentListItem;

import android.os.AsyncTask;

public class JsonAsyncCommentTask extends AsyncTask<String, Void, List<ChapterCommentListItem>> {
	CommentCallback callback;
	
	public JsonAsyncCommentTask(CommentCallback callback) {
		super();
		this.callback = callback;
	}

	@Override
	protected List<ChapterCommentListItem> doInBackground(String... params) {
		// TODO Auto-generated method stub
		List<ChapterCommentListItem> list = new ArrayList<ChapterCommentListItem>();
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(params[0]);
		HttpResponse response = null;
		try {
			response = client.execute(get);
			if(response.getStatusLine().getStatusCode()==200){
				HttpEntity entity = response.getEntity();
				String jsonString = EntityUtils.toString(entity, "urf-8");
				JSONObject jsonObject = new JSONObject(jsonString);
				String code = jsonObject.getString("code");
				if(code.equals("1")){
					JSONObject description = jsonObject.getJSONObject("description");
					JSONArray data = description.getJSONArray("data");
					for(int i=0;i<data.length();i++){
						JSONObject jsonObjectComment = data.getJSONObject(i);
						String id = jsonObjectComment.getString("id");
						String aid = jsonObjectComment.getString("aid");
						String msg = jsonObjectComment.getString("msg");
						String floor = jsonObjectComment.getString("floor");
						String username = jsonObjectComment.getString("username");
						
						ChapterCommentListItem comment = new ChapterCommentListItem(id, aid, msg, floor, username);
						list.add(comment);
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return list;
	}
	
	@Override
	protected void onPostExecute(List<ChapterCommentListItem> result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		callback.sendData(result);
	}
	
	public interface CommentCallback{
		void sendData(List<ChapterCommentListItem> list);
	}

}
